package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.CategoryDetailAdapter;
import com.rh.bmw4s.adapter.CatergoryAdapter;
import com.rh.bmw4s.adapter.GridAdapter;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.BrandBean;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.inter.OpenItemIner;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.view.SlideBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 选择车型界面
 */
public class CategoryActivity extends BaseActivity implements OpenItemIner {

    @BindView(R.id.slideBar)
    SlideBar slideBar;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.recyclerView_detail)
    LRecyclerView recyclerViewDetail;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.tv_back)
    TextView tvBack;
    private CatergoryAdapter mAdapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    //
    private CategoryDetailAdapter adapter;
    private LRecyclerViewAdapter lrecyclerViewAdapter;
    private String[] sections = {"热门", "#", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};
    private List<BrandBean> datas = new ArrayList<>();
    private HashMap<String, Integer> maps = new HashMap<>();
    private LRecyclerView recyclerViewGrid;
    private GridAdapter gridAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        ButterKnife.bind(this);
        slideBar.setOnTouchLetterListenner(new TouchLetterListenner());
        getDatas();
        getHotBrandsDatas();
        initView();
        initDetailView();
    }


    private void initView() {
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("选择车型");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CatergoryAdapter(CategoryActivity.this);
        mAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        CommonHeader header = new CommonHeader(CategoryActivity.this, R.layout.head_category_grid);
        initHead(header);
        lRecyclerViewAdapter.addHeaderView(header);
        DividerDecoration divider = new DividerDecoration.Builder(CategoryActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyclerView.addItemDecoration(divider);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.refresh();

    }

    private void initHead(CommonHeader header) {
        recyclerViewGrid = header.findViewById(R.id.recyclerView_grid);
        recyclerViewGrid.setLayoutManager(new GridLayoutManager(this, 4));
        gridAdapter = new GridAdapter(this);
        gridAdapter.setDataList(new ArrayList<BrandBean.BrandsBean>());
        LRecyclerViewAdapter gridLrecyclerViewAdapter = new LRecyclerViewAdapter(gridAdapter);
        recyclerViewGrid.setAdapter(gridLrecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(CategoryActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyclerViewGrid.addItemDecoration(divider);
        recyclerViewGrid.setLoadMoreEnabled(false);
        recyclerViewGrid.setPullRefreshEnabled(false);
        recyclerViewGrid.refresh();

        //热门车型点击事件
        gridAdapter.setHotCarTypeItemListener(new GridAdapter.HotCarTypeItemListener() {
            @Override
            public void onHotTypeItemListener(int id) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                adapter.clear();
                drawerLayout.openDrawer(Gravity.RIGHT);
                getDatas(id);
            }
        });

    }

    private void initDetailView() {
        recyclerViewDetail.setLayoutManager(new LinearLayoutManager(CategoryActivity.this));
        adapter = new CategoryDetailAdapter(CategoryActivity.this);
        //adapter.setDataList(new ArrayList<BrandBean>());
        lrecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerViewDetail.setAdapter(lrecyclerViewAdapter);
        CommonHeader header = new CommonHeader(CategoryActivity.this, R.layout.head_category_grid);
        //lRecyclerViewAdapter.addHeaderView(header);
        DividerDecoration divider = new DividerDecoration.Builder(CategoryActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyclerViewDetail.addItemDecoration(divider);
        recyclerViewDetail.setLoadMoreEnabled(false);
        recyclerViewDetail.setPullRefreshEnabled(false);
        recyclerViewDetail.refresh();
        lrecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
            }
        });
    }

    private void getHotBrandsDatas() {
        OkGo.<String>post(Constant.HOT_BRANDS)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<BrandBean.BrandsBean> bean = DealResult.getInstace().dealData(CategoryActivity.this, response, new TypeToken<BaseBean<BrandBean.BrandsBean>>() {
                        }.getType());
                        if (bean == null) {
                            return;
                        }
                        List<BrandBean.BrandsBean> beans = bean.getDatas();
                        setHotDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(CategoryActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setHotDatas(List<BrandBean.BrandsBean> beans) {
        gridAdapter.addAll(beans);
        recyclerViewGrid.refresh();
    }

    private void getDatas() {
        OkGo.<String>post(Constant.SELECTION)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<BrandBean> bean = DealResult.getInstace().dealData(CategoryActivity.this, response, new TypeToken<BaseBean<BrandBean>>() {
                        }.getType());
                        if (bean == null) {
                            return;
                        }
                        List<BrandBean> beans = bean.getDatas();
                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(CategoryActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<BrandBean> beans) {
        BrandBean.BrandsBean brandsBean = new BrandBean.BrandsBean();
        List<BrandBean.BrandsBean> brandsBeanList = new ArrayList<>();
        brandsBean.setModel_name("不限品牌");
        brandsBeanList.add(brandsBean);
        BrandBean bean = new BrandBean();
        bean.setBrands(brandsBeanList);
        bean.setLetters("#");
        beans.add(0, bean);
        for (int i = 0; i < beans.size(); i++) {
            maps.put(beans.get(i).getLetters(), i);
        }
        mAdapter.setDataList(beans);
        recyclerView.refresh();
    }

    @Override
    public void itemClick(int id) {
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        adapter.clear();
        drawerLayout.openDrawer(Gravity.RIGHT);
        getDatas(id);
    }

    @Override
    public void itemDetailClick(BrandBean.BrandsBean bean) {
        Intent i = new Intent();
        i.putExtra("bean", bean);
        Log.d("CCC", bean.getModel_name());
        this.setResult(1, i);
        this.finish();
    }

    private void getDatas(int id) {
        OkGo.<String>post(Constant.SELECTION_DETAIL)
                .tag(this)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<BrandBean> bean = DealResult.getInstace().dealData(CategoryActivity.this, response, new TypeToken<BaseBean<BrandBean>>() {
                        }.getType());
                        List<BrandBean> beans = bean.getDatas();
                        if (beans == null) {
                            return;
                        }
                        setDetailDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(CategoryActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    public void setDetailDatas(List<BrandBean> beans) {
        BrandBean.BrandsBean brandsBean = new BrandBean.BrandsBean();
        List<BrandBean.BrandsBean> brandsBeanList = new ArrayList<>();
        brandsBean.setModel_name("不限车系");
        brandsBeanList.add(brandsBean);
        BrandBean bean = new BrandBean();
        bean.setBrands(brandsBeanList);
        bean.setLetters("不限车系");
        beans.add(0, bean);
        adapter.setDataList(beans);
        recyclerViewDetail.refresh();
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.tv_back:
                if (drawerLayout != null) {
                    if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                        drawerLayout.closeDrawers();
                    }
                }
                break;
        }
    }


    class TouchLetterListenner implements SlideBar.OnTouchLetterListenner {
        @Override
        public void OnTouchLetterChange(MotionEvent event, String str) {

            tvNum.setVisibility(View.VISIBLE);
            tvNum.setText(str);
            try {
                int position = maps.get(str);
                Log.d("CCC", position + "");
                ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                tvNum.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (drawerLayout != null) {
            if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                drawerLayout.closeDrawers();
            } else super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
